package com.leetcode.Offer;

public class JZ33 {
    public boolean verifyPostorder(int[] postorder) {

        if (postorder == null || postorder.length == 0) {
            return true;
        }
        int root = postorder[postorder.length - 1];

        //寻找分界点
        int i = 0;
        for (i = 0; i < postorder.length - 1; i++) {
            if (postorder[i] > root) {
                break;
            }
        }
        //验证后半段
        int j = i;
        for (; j < postorder.length - 1; j++) {
            if (postorder[j] < root) {
                return false;
            }
        }
        //前半段
        boolean a = true;
        if (i > 0) {
            int[] ints = new int[i];
            System.arraycopy(postorder, 0, ints, 0, i);
            a = verifyPostorder(ints);
        }
        //后半段
        boolean b = true;
        if (i < postorder.length - 1) {
            int[] ints = new int[postorder.length - 1 - i];
            System.arraycopy(postorder, i, ints, 0, postorder.length - 1 - i);
            b = verifyPostorder(ints);
        }
        return a && b;
    }

    public static void main(String[] args) {
        System.out.println(new JZ33().verifyPostorder(new int[]{5,10,6,9,4}));
    }
}
